package com.rd.sys.common.fileexport;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rd.sys.common.base.CommonConstants;
import com.rd.sys.common.utils.GetWebConfig;

/**
 * 解析导出任务
 */
public class ParseExportXML {
    static Logger logger = LoggerFactory.getLogger(ParseExportXML.class);

    private Document doc;

    private static ParseExportXML singleton_instance = null;

    private String exportcfg;

    private ParseExportXML() {
        exportcfg = CommonConstants.ExportConstants.EXPORT_CONFIG_FILE_NAME;

        String resourcetype = GetWebConfig.getValue("resourcetype");

        exportcfg = exportcfg.replaceAll("#", resourcetype);

        logger.info("success read export config file : {}", exportcfg);

        InputStream in = this.getClass().getResourceAsStream("/" + exportcfg);
        SAXReader reader = new SAXReader();
        try {
            doc = reader.read(in);
        } catch (Exception ex) {
            throw new RuntimeException("get export configuration error");
        }
    }

    synchronized public static ParseExportXML getExportXml() {
        if (singleton_instance == null) {
            singleton_instance = new ParseExportXML();
        }
        return singleton_instance;
    }

    /**
     * 根据传入的导出类型，得到需要的参数
     * 
     * @param type
     *            导出类型
     * @return
     */
    public HashMap<String, Object> getData(String type) {
        HashMap<String, Object> map = null;
        Element root = doc.getRootElement();
        // 得到task节点列表
        List<?> tasknodes = root.elements(CommonConstants.ExportConstants.EXPORT_CONFIG_FILE_NODE_TASK);
        for (Iterator<?> it = tasknodes.iterator(); it.hasNext();) {
            Element elmtask = (Element) it.next();
            Attribute attribute = elmtask.attribute(CommonConstants.ExportConstants.EXPORT_CONFIG_FILE_NODE_TYPE);
            // 选出与传入导出类型相同的task节点
            if (attribute.getText().trim().equals(type)) {
                map = new HashMap<String, Object>();

                // 导出文件的信息头
                String head = elmtask.element(CommonConstants.ExportConstants.EXPORT_CONFIG_FILE_NODE_HEAD).getText()
                        .trim();

                // 导出操作处理类
                String operator = elmtask.element(CommonConstants.ExportConstants.EXPORT_CONFIG_FILE_NODE_OPERATOR)
                        .getText().trim();

                map.put(CommonConstants.ExportConstants.EXPORT_CONFIG_FILE_NODE_TYPE, type);
                map.put(CommonConstants.ExportConstants.EXPORT_CONFIG_FILE_NODE_HEAD, head);
                map.put(CommonConstants.ExportConstants.EXPORT_CONFIG_FILE_NODE_OPERATOR, operator);
            }
        }

        return map;
    }
}